<?php
date_default_timezone_set('Europe/London');
 
$message = '';
$log_path = dirname(__FILE__).'/repost.log';
$action = empty($_REQUEST['action']) ? '' : $_REQUEST['action'];
$repost_host = (empty($_REQUEST['host']) ? 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['SCRIPT_NAME'] : $_REQUEST['host']);
$href = '?host='.urlencode($repost_host);	

if ($action == 'change_target') {
	$message = 'Target changed.';
}

if ($action == 'truncate') {
	write_log_file($log_path);
	$message = 'Log file truncated.';
}

// delete request
if ($action == 'delete') {
	$requests = file_get_contents($log_path);
	$requests = json_decode($requests, true);
	$reqid = $_REQUEST['reqid'];

	unset($requests[$reqid]);
	write_log_file($log_path, $requests);

	$message = 'Request #'.$reqid.' deleted.';
}

// forward request
if ($action == 'forward') {
	if (file_exists($log_path)) {
		$requests = file_get_contents($log_path);
		$requests = json_decode($requests, true);
		$reqid = $_REQUEST['reqid'];
		
		$request = $requests[$reqid];
		$method = $request['info']['server']['REQUEST_METHOD'];
		
		$forward_request = array(
				 'http' => array(
					 'method' => $method,
					 'header' => get_header_from_request($request),
					 'content' => $request['request']['body'],
				 )
			 );
		
		$url = $repost_host;
		if (!empty($request['info']['server']['QUERY_STRING'])) $url .= '?'.$request['info']['server']['QUERY_STRING'];
		
		$context = stream_context_create($forward_request);
		$result = file_get_contents($url, false, $context);
		$message = 'Forwarded request #'.$reqid.' '.$method;
		$message .= ' <a href="'.$href.'&amp;reqid='.$reqid.'&amp;action=forward">Resend</a>';
		$message .= '<br/><textarea cols="80" rows="5">'.$result.'</textarea><br/>';
	}
}

// ---

$is_request = !empty($_REQUEST) && empty($action);

// load the past requests
$requests = Array();
$log_size = 0;
if (file_exists($log_path)) {
	$requests = file_get_contents($log_path);
	$log_size = strlen($requests);
	$requests = json_decode($requests, true);
}

// ---

if ($is_request) {
	// save the new request
	$body = @file_get_contents('php://input');
	$requests[] = Array('request' => Array('request' => $_REQUEST, 'body' => $body), 'info' => Array('server' => $_SERVER, 'timestamp' => time()));
	write_log_file($log_path, $requests);
	
	?>
	<!-- form method="POST">
		Key1 = <input type="text" name="key1" value="val1"/>
		<br/>
		Key2 = <input type="text" name="key2" value="val2"/>
		<input type="submit" />
	</form -->
	<?php
} else {
	print_html_pre();
	
	if (empty($requests)) $message = 'The request log is empty. Submit POST or GET requests to this page to populate the log.';

	if ($message) {
		print '<div class="message">'.$message.'</div>';		
	}
	
	// show stats
	print '<a href="'.$href.'&amp;action=refresh">Refresh</a>';
	
	// show individual requests
	if (count($requests)) {
		print '<div class="command-panel">';
		print count($requests) . ' requests. ';
		$log_size_human = get_human_size($log_size);
		print 'Log file size = '. $log_size_human['number'].' '.$log_size_human['unit'];
		print ' <a href="'.$href.'&amp;action=truncate" class="warning">Truncate log file</a>';
		$last_index = count($requests) - 1;
		print '<br/>';
		print 'Last request = '.get_request_time($requests[$last_index]);

		print '<form method="post">';
		print '<input type="hidden" name="action" value="change_target"/>';
		print 'Target of forwarded requests <input type="text" style="width:30em;" name="host" value="'.$repost_host.'" />';
		print '<input type="submit" name="" value="update" />';
		print '</form>';
		print '</div>';
		
		foreach ($requests as $number => $request) {
			print '<div class="request" id="r-'.$number.'">';
			print 'Request #'.$number.': '.$request['info']['server']['REQUEST_METHOD'].' at '.get_request_time($request);
			// print '<br/>';
			print ' | <a href="'.$href.'&amp;action=forward&amp;reqid='.$number.'">Forward this request</a>';
			print ' | <a href="'.$href.'&amp;action=expand&amp;reqid='.$number.'#r-'.$number.'">Show all information</a>';
			print ' | <a href="'.$href.'&amp;action=delete&amp;reqid='.$number.'" class="warning">Delete</a>';
			print '<br/>';
			/*
			foreach ($request['request']['request'] as $param => $value) {
				print $param.' = '.$value;
				print '<br/>';
			}
			*/
			if ($action == 'expand' && $number == $_REQUEST['reqid']) {
				print '<pre>';
				ob_start();
				print_r($request);
				print (htmlspecialchars(ob_get_clean()));
				print '</pre>';
			} else {
				print '$_REQUEST = '.json_encode($request['request']['request']);
			}
			print '</div>';
		}
		
		//var_dump($requests);
		//print_r($_SERVER);
	}
	
	print_html_post();
}

function get_request_time($request) {
	return strftime('%H:%M:%S on %a %d %b %Y', $request['info']['timestamp']);
} 

function print_html_post() {
	?>
		<p class="footer">Repost by Goffer Looney. Version: 20/03/2012.</p>
		</body>
	</html>
	<?php
}

function print_html_pre() {
	?>
	<html>
		<head>
			<title>Repost</title>
			<style type="text/css">
				.request {background-color:#F0FFF0; border: 2px solid green; margin-bottom: 0.5em; padding: 0.25em;}
				/* .command-panel {background-color:#F0F0FF; border: 2px solid blue; margin-bottom: 0.5em; padding: 0.25em;} */
				.command-panel {background-color:#A0A0FF; color: white; border: 2px solid blue; margin-bottom: 0.5em; padding: 0.25em;}
				a {
					background-color: lightgrey; color: black; text-decoration:none; 
					padding: 1px;
					margin-bottom: 2px;
					display: inline-block;
					border-top: 2px solid #E0E0E0; 
					border-left: 2px solid #E0E0E0;
					border-right: 2px solid grey;
					border-bottom: 2px solid grey;
				}
				h1 {text-align: center; font-size: xx-large;}
				body {font-family: Arial; font-size: small;}
				.warning {
					background-color: #FF8080; 
					color: black;
					text-decoration:none; 
					border-top-color: #FFE0E0; 
					border-left-color: #FFE0E0;
					border-right-color: #FF4040;
					border-bottom-color: #FF4040;
				}
				.message {background-color: #FFE0A0; padding: 0.25em; margin-bottom: 0.5em;}
				.message textarea { width: 100%; height: 10em;}
				.footer {color: grey;}
			</style>
		</head>
		<body>
			<h1>Repost</h1>
	<?php
}

function get_human_size($log_size) {
	$number = $log_size;
	$unit = 'B';
	foreach(array('B', 'KB', 'MB', 'GB') as $unit) {
		if ($number > 1024) {
			$number /= 1024.0;
		} else {
			break;
		}
	}
	return array('number' => (int)$number, 'unit' => $unit);
}

function write_log_file($log_path, $requests=array()) { 
	file_put_contents($log_path, json_encode($requests));
}

function get_header_from_request($request) {
	$vars = array();
	$server = $request['info']['server'];
	
	$params = array('CONTENT_TYPE' => 'Content-Type', 'HTTP_USER_AGENT' => 'User-Agent', 'HTTP_HOST' => 'Host', 
					'HTTP_ACCEPT' => 'Accept', 'HTTP_ACCEPT_LANGUAGE' => 'Accept_language', 
					'HTTP_ACCEPT_ENCODING' => 'Accept-Encoding');
	foreach ($params as $server_name => $http_name)
	if (!empty($server[$server_name])) {
		$vars[$http_name] = $server[$server_name];
	} 
	
	$ret = '';
	foreach ($vars as $key => $val) {
		$ret .= $key.': '.$val."\r\n";
	}
	
	return $ret;
}

?>